package com.gnerv.author.freemarker.tag;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gnerv.author.entity.Article;
import com.gnerv.author.entity.ArticleConfig;
import com.gnerv.author.entity.Commentary;
import com.gnerv.author.freemarker.FreemarkerComponent;
import com.gnerv.author.service.IArticleConfigService;
import com.gnerv.author.service.IArticleService;
import com.gnerv.author.service.ICommentaryService;
import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapperBuilder;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Gnerv LiGen
 * @description
 * @data 2019/4/3
 */
@FreemarkerComponent("g_commentary")
public class CommentaryTagDirective implements TemplateDirectiveModel {

    @Autowired
    ICommentaryService commentaryService;

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
        String aId = StringUtils.isEmpty(map.get("articleId")) ? null : map.get("articleId").toString();
        List<Commentary> commentaries = commentaryService.listCommentary(new Commentary(aId));
        TemplateModel tm = builder.build().wrap(commentaries);
        environment.setVariable("commentarys", tm);
        templateDirectiveBody.render(environment.getOut());
    }

}
